﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.DirectX.DirectInput;
using KGE.Define;

namespace KGE.BasicCOM
{
    public class KeyboardCOM : GameCOM
    {
        //Key banKey;
        KeyStream keyStream;
        bool[] keyboardStateBackup = new bool[256];
        public KeyboardCOM(Game g)
            : base(g)
        {
            DisableAll();
            Enable = true;
            keyStream = new KeyStream();
        }
        public bool IsIdle
        {
            get
            {
                foreach (bool b in keyboardStateBackup)
                {
                    if (b)
                    {
                        return false;
                    }
                }
                return true;
            }
        }
        new public string ToString()
        {
            return keyStream.ToString();
        }
        public override void Code()
        {
            keyStream.Update();
            KeyboardState keyboardState = game.Devices.DKeyboardDev.GetCurrentKeyboardState();
            for (int i = 0; i < keyboardStateBackup.Length; i++)
            {
                if (keyboardState[(Key)i])
                {
                    if (keyboardStateBackup[i])
                    {
                        keyboardStateBackup[i] = true;

                        foreach (GameCOM gc in game.GameComs)
                        {
                            if (gc.Controllable)
                                gc.SetKeyboardEvent((Key)i, KeyState.Hold);
                        }
                    }
                    else
                    {
                        keyboardStateBackup[i] = true;

                        foreach (GameCOM gc in game.GameComs)
                        {
                            if (gc.Controllable)
                                gc.SetKeyboardEvent((Key)i, KeyState.Down);
                        }

                        KeyStream.KeyInfo ki = new KeyStream.KeyInfo();
                        ki.Key = (Key)i;
                        ki.State = KeyState.Down;
                        keyStream.Add(ki);
                    }
                }
                else
                {
                    if (keyboardStateBackup[i])
                    {
                        keyboardStateBackup[i] = false;

                        foreach (GameCOM gc in game.GameComs)
                        {
                            if (gc.Controllable)
                                gc.SetKeyboardEvent((Key)i, KeyState.Up);
                        }
                    }
                }
            }
        }
    }
}
